package com.example.maoyanmovie.ui.activity;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.example.maoyanmovie.R;
import com.example.maoyanmovie.databinding.ActivityMainBinding;
import com.example.maoyanmovie.ui.fragment.CinemaFragment;
import com.example.maoyanmovie.ui.fragment.ComingFragment;
import com.example.maoyanmovie.ui.fragment.HomeFragment;
import com.example.maoyanmovie.ui.fragment.MineFragment;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private HomeFragment homeFragment;
    private CinemaFragment cinemaFragment;
    private ComingFragment comingFragment;
    private MineFragment mineFragment;
    private Fragment currentFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initFragments();
        initBottomNavigation();
        showFragment(homeFragment);
    }

    private void initFragments() {
        homeFragment = new HomeFragment();
        cinemaFragment = new CinemaFragment();
        comingFragment = new ComingFragment();
        mineFragment = new MineFragment();
    }

    private void initBottomNavigation() {
        binding.bottomNavigationView.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.navigation_home) {
                showFragment(homeFragment);
                return true;
            } else if (itemId == R.id.navigation_cinema) {
                showFragment(cinemaFragment);
                return true;
            } else if (itemId == R.id.navigation_coming) {
                showFragment(comingFragment);
                return true;
            } else if (itemId == R.id.navigation_mine) {
                showFragment(mineFragment);
                return true;
            }
            return false;
        });
    }

    private void showFragment(Fragment fragment) {
        if (currentFragment == fragment) {
            return;
        }

        if (!fragment.isAdded()) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragmentContainer, fragment)
                    .commit();
        }

        if (currentFragment != null) {
            getSupportFragmentManager().beginTransaction()
                    .hide(currentFragment)
                    .show(fragment)
                    .commit();
        } else {
            getSupportFragmentManager().beginTransaction()
                    .show(fragment)
                    .commit();
        }

        currentFragment = fragment;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}
